// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 为所有卡片添加淡入动画
    const cards = document.querySelectorAll('.todo-card, .stat-card, .card');
    cards.forEach((card, index) => {
        card.style.animation = `fadeIn 0.5s ease-in-out ${index * 0.05}s both`;
    });

    // 自动隐藏提示消息
    const alerts = document.querySelectorAll('.alert');
    alerts.forEach(alert => {
        setTimeout(() => {
            const bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        }, 5000); // 5秒后自动关闭
    });

    // 确认删除
    const deleteButtons = document.querySelectorAll('[data-bs-target^="#deleteModal"]');
    deleteButtons.forEach(button => {
        button.addEventListener('click', function() {
            const todoTitle = this.closest('.todo-card').querySelector('h5').textContent.trim();
            console.log('准备删除:', todoTitle);
        });
    });

    // 复选框动画
    const checkboxes = document.querySelectorAll('.todo-card .form-check-input');
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            const card = this.closest('.todo-card');
            if (this.checked) {
                card.style.opacity = '0.5';
                card.style.transition = 'opacity 0.3s';
            }
        });
    });

    // 搜索框自动聚焦（仅在桌面设备）
    if (window.innerWidth > 768) {
        const searchInput = document.querySelector('input[name="search"]');
        if (searchInput && !searchInput.value) {
            // searchInput.focus(); // 可选：自动聚焦搜索框
        }
    }

    // 截止日期提醒
    const now = new Date();
    const todoCards = document.querySelectorAll('.todo-card');
    
    todoCards.forEach(card => {
        const dueDateBadge = card.querySelector('.badge.bg-info, .badge.bg-danger');
        if (dueDateBadge) {
            const dateText = dueDateBadge.textContent.trim();
            // 可以在这里添加更多的日期相关逻辑
        }
    });

    // 表单验证增强
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            const titleInput = this.querySelector('#title');
            if (titleInput && !titleInput.value.trim()) {
                e.preventDefault();
                titleInput.focus();
                alert('请输入任务标题');
                return false;
            }
        });
    });

    // 统计数字动画
    animateNumbers();

    // 添加键盘快捷键支持
    document.addEventListener('keydown', function(e) {
        // Ctrl/Cmd + N: 新建任务
        if ((e.ctrlKey || e.metaKey) && e.key === 'n') {
            e.preventDefault();
            const createButton = document.querySelector('a[href*="create"]');
            if (createButton) {
                createButton.click();
            }
        }
        
        // Ctrl/Cmd + K: 聚焦搜索框
        if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
            e.preventDefault();
            const searchInput = document.querySelector('input[name="search"]');
            if (searchInput) {
                searchInput.focus();
                searchInput.select();
            }
        }
    });
});

// 数字动画函数
function animateNumbers() {
    const statNumbers = document.querySelectorAll('.stat-card h2');
    
    statNumbers.forEach(element => {
        const target = parseInt(element.textContent);
        let current = 0;
        const increment = target / 50; // 动画速度
        const timer = setInterval(() => {
            current += increment;
            if (current >= target) {
                element.textContent = target;
                clearInterval(timer);
            } else {
                element.textContent = Math.floor(current);
            }
        }, 20);
    });
}

// 工具函数：格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    const now = new Date();
    const diff = date - now;
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (days < 0) {
        return `已逾期 ${Math.abs(days)} 天`;
    } else if (days === 0) {
        return '今天到期';
    } else if (days === 1) {
        return '明天到期';
    } else if (days <= 7) {
        return `${days} 天后到期`;
    } else {
        return date.toLocaleDateString('zh-CN');
    }
}

// 工具函数：显示提示消息
function showToast(message, type = 'info') {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    const container = document.querySelector('.container');
    if (container) {
        container.insertBefore(alertDiv, container.firstChild);
        
        // 自动关闭
        setTimeout(() => {
            const bsAlert = new bootstrap.Alert(alertDiv);
            bsAlert.close();
        }, 3000);
    }
}

// 工具函数：确认对话框
function confirmAction(message, callback) {
    if (confirm(message)) {
        callback();
    }
}

// 导出函数供其他脚本使用
window.todoApp = {
    formatDate,
    showToast,
    confirmAction
};

